<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" size="small" style="margin-left: 10px;" type="primary" icon="el-icon-edit"
                 @click="handleCreate">
        添加
      </el-button>
      <el-button class="filter-item" size="small" style="margin-left: 10px;" type="danger" icon="el-icon-delete"
                 @click="batchDelete">
        删除
      </el-button>
    </div>
    <el-table
      ref="roleTable"
      v-loading="listLoading"
      :data="roleList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column label="角色名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色标识" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleCode }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色描述" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据权限" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.dsType === 1">全部</span>
          <span v-else-if="scope.row.dsType === 2">本级及子级</span>
          <span v-else-if="scope.row.dsType === 3">本级</span>
          <span v-else-if="scope.row.dsType === 4">自定义</span>
          <span v-else>未知标识</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="handlerOpenGranted(row.id)">
            授权
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" style="text-align: right" :total="total" :page.sync="listQuery.current" :limit.sync="listQuery.size" @pagination="getRoles"/>

    <!-- 添加/编辑 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="center" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="temp.roleName"/>
        </el-form-item>
        <el-form-item label="角色标识" prop="roleName">
          <el-input v-model="temp.roleCode" :disabled="roleCodeDisabled"/>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="temp.description"/>
        </el-form-item>
        <el-form-item label="数据权限" prop="dsType">
          <el-select v-model="temp.dsType" placeholder="请选择数据权限" @change="dataScopeChange">
            <el-option
              v-for="item in dataScopeSelect"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div v-show="treeShow" style="padding-left: 5rem" class="dialog-auto-scroll">
        <el-tree
          ref="grantedDeptTree"
          :data="grantedDeptTree.trees"
          show-checkbox
          node-key="id"
          :default-checked-keys="grantedDeptTree.defaultCheckedKeys"
          :props="grantedDeptTree.props">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create'? createData() : updateData() ">
          提交
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="grantedMenuTree.title" :visible.sync="grantedVisible">
      <div class="dialog-auto-scroll">
        <el-tree
          ref="grantedTree"
          :data="grantedMenuTree.trees"
          show-checkbox
          node-key="id"
          :default-checked-keys="grantedMenuTree.defaultCheckedKeys"
          :props="grantedMenuTree.props"
          :default-expand-all="true">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="checkAll">
          全选/反选
        </el-button>
        <el-button @click="grantedVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="handlerGranted">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Pagination from '@/components/Pagination'
  import { getRolesPage, createRole, updateRole, deleteRole, batchDeleteRole, getRoleMenus, granted } from '@/api/role'
  import { getDeptTree } from '@/api/dept'
  import { getTreeCheckedKeys } from '@/utils/common'

  export default {
    name: 'Role',
    components: { Pagination },
    data() {
      return {
        roleCodeDisabled: false,
        grantedRoleId: '',
        grantedVisible: false,
        treeShow: false,
        checkAllToggle: false,
        grantedMenuTree: {
          title: '分配权限',
          trees: [],
          defaultCheckedKeys: [],
          props: {
            children: 'children',
            label: 'title'
          }
        },
        grantedDeptTree: {
          trees: [],
          defaultCheckedKeys: [],
          props: {
            children: 'children',
            label: 'name'
          }
        },
        dataScopeSelect: [
          {
            value: 1,
            label: '全部'
          }, {
            value: 2,
            label: '本级及下级'
          }, {
            value: 3,
            label: '本级'
          }, {
            value: 4,
            label: '自定义'
          }
        ],
        defaultScopeSelect: '',
        batchIds: [],
        listQuery: {
          current: 1,
          size: 10
        },
        total: 0,
        roleList: [],
        listLoading: true,
        dialogStatus: '',
        dialogFormVisible: false,
        activeDataScope: '',
        temp: {
          id: undefined,
          roleName: '',
          roleCode: '',
          description: '',
          created: '',
          dsType: '',
          dsScope: ''
        },
        textMap: {
          update: '编辑角色',
          create: '添加角色'
        },
        rules: {
          roleName: [{ required: true, message: '请输入角色标识', trigger: 'blur' }],
          description: [{ required: true, message: '请输入角色描述', trigger: 'blur' }],
          dsType: [{ required: true, message: '请选择活动区域', trigger: 'change' }]
        }
      }
    },
    created() {
      this.getRoles()
    },
    methods: {
      deptTree() {
        getDeptTree().then(({ data }) => {
          this.grantedDeptTree.trees = data
          this.dataScopeChange(this.temp.dsType)
          this.grantedDeptTree.defaultCheckedKeys = getTreeCheckedKeys(this.temp.dsScope.split(','), data)
        }).catch(error => {
          console.log(error)
        })
      },
      /**
       * 全选/反选
       */
      checkAll() {
        if (!this.checkAllToggle) {
          this.$refs.grantedTree.setCheckedNodes(this.grantedMenuTree.trees)
          this.checkAllToggle = true
        } else {
          const res = this.$refs.grantedTree
          const nodes = res.getCheckedNodes(true, true)
          if (typeof this.grantedMenuTree.trees !== 'undefined') {
            this.grantedMenuTree.trees.forEach(element => {
              res.setChecked(element, this.checkAllToggle, true)
            })
          }

          if (typeof nodes !== 'undefined') {
            nodes.forEach(node => {
              res.setChecked(node, !this.checkAllToggle, true)
            })
          }
        }
      },
      /**
       * 自定义弹出部门树
       */
      dataScopeChange(value) {
        this.treeShow = value === this.dataScopeSelect[3].value
      },
      // 重置分页条件
      resetListQuery(size) {
        const pages = Math.ceil((this.total - size) / this.listQuery.size)
        const current = this.listQuery.current > pages ? pages : this.listQuery.current
        this.listQuery.current = current < 1 ? 1 : current
      },
      // 获取角色分页列表
      getRoles() {
        this.listLoading = true
        getRolesPage(this.listQuery).then(({ data }) => {
          this.roleList = data.records
          this.total = data.total
          this.listLoading = false
        }).catch(error => {
          console.log(error)
          this.$message.error(error)
        })
      },
      // 重置表单
      resetTemp() {
        this.temp = {
          id: undefined,
          roleName: '',
          roleCode: '',
          description: '',
          created: '',
          dsType: '',
          roleDeptIds: []
        }
      },
      // 弹出框
      handleCreate() {
        this.roleCodeDisabled = false
        this.deptTree()
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 设置部门id
      setDeptIds() {
        if (this.temp.dsType === this.dataScopeSelect[3].value) {
          this.temp.roleDeptIds = this.$refs.grantedDeptTree.getCheckedKeys().concat(this.$refs.grantedDeptTree.getHalfCheckedKeys())
        }
      },
      // 创建
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.setDeptIds()
            createRole(this.temp).then(() => {
              this.getRoles()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 3000
              })
            }).catch(error => {
              console.log(error)
            })
          }
        })
      },
      // 弹出框
      handleUpdate(row) {
        this.roleCodeDisabled = true
        this.deptTree()
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.created)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      // 修改
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.setDeptIds()
            const tempData = Object.assign({}, this.temp)
            console.log(tempData)
            updateRole(tempData).then(() => {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getRoles()
            }).catch()
          }
        })
      },
      // 删除单条
      handleDelete(id) {
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteRole(id).then(() => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.resetListQuery(1)
            this.getRoles()
          }).catch(() => {
            this.$notify.error({
              title: '错误',
              message: '删除失败'
            })
          })
        })
      },
      // 获取多选的值
      handleSelectionChange(select) {
        this.batchIds = select
      },
      // 批量删除
      batchDelete() {
        if (this.batchIds.length === 0) {
          this.$message.warning('请至少选中一行数据')
          return
        }
        const ids = []
        this.batchIds.map(item => {
          ids.push(item.id)
        })
        this.$confirm('您确定要删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchDeleteRole(ids).then(() => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.$refs.roleTable.clearSelection()
            this.resetListQuery(ids.length)
            this.getRoles()
          }).catch(() => {
            this.$notify.error({
              title: '错误',
              message: '删除失败'
            })
          })
        }).catch(() => {
          this.$refs.roleTable.clearSelection()
        })
      },
      /**
       * 打开授权页
       */
      handlerOpenGranted(id) {
        getRoleMenus(id).then(({ data }) => {
          this.grantedMenuTree.trees = data.allTrees
          this.grantedMenuTree.defaultCheckedKeys = getTreeCheckedKeys(data.roleMenuIds, data.allTrees)
          this.grantedRoleId = id
          this.grantedVisible = true
        })
      },
      handlerGranted() {
        let menuIds = this.$refs.grantedTree.getCheckedKeys()
        const hafCheckedIds = this.$refs.grantedTree.getHalfCheckedKeys()
        menuIds = menuIds.concat(hafCheckedIds)
        granted({
          roleId: this.grantedRoleId,
          menuIds: menuIds
        }).then(() => {
          this.$notify.success({
            title: '成功',
            message: '授权成功'
          })
          this.grantedRoleId = ''
        }).catch(() => {
          this.$notify.error({
            title: '错误',
            message: '授权失败'
          })
        })
        this.grantedVisible = false
      }
    }
  }
</script>

<style scoped type="scss">
</style>
